﻿using System;
using System.Web.Mvc;
using System.Linq;
using BabyShop.WebSite.Exts.Attributes;
using BabyShop.WebSite.Models;
using BabyShop.WebSite.Services;
using BabyShop.WebSite.ViewModels;

namespace BabyShop.WebSite.Areas.SysManage.Controllers
{
    public class ProductTypeController : BaseController
    {
        private readonly ProductTypeService _productTypeService = new ProductTypeService();

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Create()
        {
            EnumServices enumServices = new EnumServices();
            SelectListItem[] productTypeList = enumServices.GetParentProductTypes(Guid.Empty)
                .Select(p => new SelectListItem {Text = p.ProductTypeName, Value = p.ProductTypeGuid.ToString()}).ToArray();
            ViewBag.ProductTypeList = productTypeList;
            return View(new ProductType {ProductTypeGuid = Guid.Empty});
        }

        public ActionResult Edit(Guid keyGuid)
        {
            var productType = _productTypeService.GetProductTypeByGuid(keyGuid);
            if (productType == null)
                return Content("Can not find the data in the database.");

            EnumServices enumServices = new EnumServices();
            SelectListItem[] productTypeList = enumServices.GetParentProductTypes(keyGuid)
                .Select(p => new SelectListItem { Text = p.ProductTypeName, Value = p.ProductTypeGuid.ToString() }).ToArray();
            ViewBag.ProductTypeList = productTypeList;
            return View("Create", productType);
        }

        [HttpPost]
        public ActionResult Create(ProductType productType)
        {
            bool execSucc = _productTypeService.Save(productType, CurrentUser.UserGuid);
            return Json(execSucc
                            ? new AjaxResult {ShowMsg = "保存成功"}
                            : new AjaxResult {ErrorCode = 1001, ShowMsg = "保存失败"});
        }

        [HttpPost]
        public ActionResult ProductTypeList([JqGridModelBinder]JqGridViewModel jqGridViewModel)
        {
            string[] searchCols = new[]
                                      {
                                          "ProductTypeGuid",
                                          "ProductTypeName", "ParentProductType.ProductTypeName",
                                          "CommonColumns.LastModified", "CommonColumns.IsDelete"
                                      };
            return Json(_productTypeService.GetJqGridSearchResult(jqGridViewModel, searchCols));
        }

        [HttpPost]
        public ActionResult Remove(Guid keyGuid)
        {
            bool execSucc = _productTypeService.Delete(keyGuid, CurrentUser.UserGuid);
            return Json(new AjaxResult { ShowMsg = execSucc ? "删除成功" : "删除失败", ErrorCode = execSucc ? 0 : 1001 });
        }
    }
}
